Python provides multiple frameworks to help developers create web applications, from inbuild http.server
to lots of 3rd party modules.
In this section we will discuss about django
and flask
two most popular web frameworks.
In [ ]:
In [ ]:
pip install django
django
installation on my machine
$:>pip3.6 install django --user
Collecting django
Downloading Django-2.0.3-py3-none-any.whl (7.1MB)
100% |████████████████████████████████| 7.1MB 132kB/s
Requirement already satisfied: pytz in /home/mayank/.local/lib64/python3.6/site-packages (from django)
Installing collected packages: django
Successfully installed django-2.0.3
django
projects can be created using the following command
django-admin startproject <project_name>
Example:
django-admin startproject training
In the above example, we are asking django
to create a project called training
, which fill create the following files & folders
$ tree training/
training/
├── training
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── manage.py
The outer mysite/ root directory is just a container for your project. Its name doesn’t matter to Django; you can rename it to anything you like.
manage.py: A command-line utility that lets you interact with this Django project in various ways. You can read all the details about manage.py in django-admin and manage.py.
The inner mysite/ directory is the actual Python package for your project. Its name is the Python package name you’ll need to use to import anything inside it (e.g. mysite.urls).
mysite/__init__.py: An empty file that tells Python that this directory should be considered a Python package. If you’re a Python beginner, read more about packages in the official Python docs.
mysite/settings.py: Settings/configuration for this Django project. Django settings will tell you all about how settings work.
mysite/urls.py: The URL declarations for this Django project; a “table of contents” of your Django-powered site. You can read more about URLs in URL dispatcher.
mysite/wsgi.py: An entry-point for WSGI-compatible web servers to serve your project. See How to deploy with WSGI for more details.
In [ ]:
It is the command-line
utility that lets us interact with this Django project. list of full options is as follows
$ python manage.py
Type 'manage.py help <subcommand>' for help on a specific subcommand.
Available subcommands:
[auth]
changepassword
createsuperuser
[contenttypes]
remove_stale_contenttypes
[django]
check
compilemessages
createcachetable
dbshell
diffsettings
dumpdata
flush
inspectdb
loaddata
makemessages
makemigrations
migrate
sendtestemail
shell
showmigrations
sqlflush
sqlmigrate
sqlsequencereset
squashmigrations
startapp
startproject
test
testserver
[sessions]
clearsessions
[staticfiles]
collectstatic
findstatic
runserver
In [ ]:
In [ ]:
In [ ]:
In [ ]:
goto the training
folder where manage.py
file is located and execute the following command
python3 manage.py runserver
python3 manage.py runserver 8080
In [ ]:
In [ ]:
# polls/view.py
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
def index(request):
return HttpResponse("<html><body><h1>!!! नमस्कार भारत !!!</h1></body></html>")
We need to create a urls.py
file in polls
folder. Using it we can define all the app urls relative to app.
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
In [2]:
#### `training/urls.py`
In [ ]:
from django.urls import include, path
from django.contrib import admin
urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
! ## TODO ##
The include() function allows referencing other URLconfs. Whenever Django encounters include(), it chops off whatever part of the URL matched up to that point and sends the remaining string to the included URLconf for further processing.
The idea behind include() is to make it easy to plug-and-play URLs. Since polls are in their own URLconf (polls/urls.py), they can be placed under “/polls/”, or under “/fun_polls/”, or under “/content/polls/”, or any other path root, and the app will still work.
NOTE:
When to use include()
You should always use include() when you include other URL patterns. admin.site.urls is the only exception to this.
Details of path
route is a string that contains a URL pattern. When processing a request, Django starts at the first pattern in urlpatterns and makes its way down the list, comparing the requested URL against each pattern until it finds one that matches.
Patterns don’t search GET and POST parameters, or the domain name. For example, in a request to https://www.example.com/myapp/, the URLconf will look for myapp/. In a request to https://www.example.com/myapp/?page=3, the URLconf will also look for myapp/.
When Django finds a matching pattern, it calls the specified view function with an HttpRequest object as the first argument and any “captured” values from the route as keyword arguments. We’ll give an example of this in a bit.
Arbitrary keyword arguments can be passed in a dictionary to the target view. We aren’t going to use this feature of Django in the tutorial.
Naming your URL lets you refer to it unambiguously from elsewhere in Django, especially from within templates. This powerful feature allows you to make global changes to the URL patterns of your project while only touching a single file.
When you’re comfortable with the basic request and response flow, read part 2 of this tutorial to start working with the database.
In [ ]:
NOTE:
For databases other than SQLite
If you’re using a database besides SQLite, make sure you’ve created a database by this point. Do that with “CREATE DATABASE database_name;” within your database’s interactive prompt.
Also make sure that the database user provided in mysite/settings.py has “create database” privileges. This allows automatic creation of a test database which will be needed in a later tutorial.
If you’re using SQLite, you don’t need to create anything beforehand - the database file will be created automatically when it is needed.
In [ ]:
In [ ]:
In [ ]:
In [ ]:
Now we’ll define your models – essentially, your database layout, with additional metadata.
A model is the single, definitive source of truth about your data. It contains the essential fields and behaviors of the data you’re storing. Django follows the DRY Principle. The goal is to define your data model in one place and automatically derive things from it.
This includes the migrations - unlike in Ruby On Rails, for example, migrations are entirely derived from your models file, and are essentially just a history that Django can roll through to update your database schema to match your current models.
It is a three step process
python manage.py makemigrations
to create migrations for those changespython manage.py migrate
to apply those changes to the database.In our simple poll app, we’ll create two models: Question and Choice. A Question has a question and a publication date. A Choice has two fields: the text of the choice and a vote tally. Each Choice is associated with a Question.
These concepts are represented by simple Python classes. Edit the polls/models.py file so it looks like this:
# polls/models.py
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
Now, lets update the training/settings.py
to reflect the changes by adding polls.apps.PollsConfig
to the INSTALLED_APPS
section.
INSTALLED_APPS = [
'polls.apps.PollsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
Now lets run the following command to create the necessary migrations
$ python manage.py makemigrations polls
Migrations for 'polls':
polls/migrations/0001_initial.py
- Create model Choice
- Create model Question
- Add field question to choice
Now lets run the following command to create the necessary tables in database
$ python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, polls, sessions
Running migrations:
Applying polls.0001_initial... OK
In [ ]:
In [ ]:
python manage.py createsuperuser
In [ ]:
# polls/admin.py
from django.contrib import admin
from .models import Question
admin.site.register(Question)
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
### Hello World - A Static Website
In [ ]:
# from flask import Flask
# app = Flask(__name__)
# @app.route('/')
# def hello_world():
# return 'Hello World!'
# if __name__ == '__main__':
# app.run()
In [ ]: